package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/dtos"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

func AddProductFunction(pf models.ProductFunction, ctx context.Context, dic *di.Container) (id string, edgeXerr errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	addProductFunction, err := dbClient.AddProductFunction(pf)
	if err != nil {
		return "", errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf(
		"Product Function created on DB successfully. Product Function ID: %s, Correlation-ID: %s ",
		addProductFunction.Id,
		correlation.FromContext(ctx),
	)

	return addProductFunction.Id, nil
}

// 通过产品id查询产品功能
func AllFunctionsByProductId(offset int, limit int, productId string, dic *di.Container) (productFunctions []dtos.ProductFunction, totalCount uint32, err errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	functions, err := dbClient.AllFunctionsByProductId(offset, limit, productId)
	if err == nil {
		totalCount, err = dbClient.AllFunctionCountByProductId(productId)
	}
	if err != nil {
		return productFunctions, totalCount, errors.NewCommonEdgeXWrapper(err)
	}
	productFunctions = make([]dtos.ProductFunction, len(functions))
	for i, pf := range functions {
		productFunctions[i] = dtos.FromProductFunctionModelToDto(pf)
	}
	return productFunctions, totalCount, nil
}

// 批量删除产品功能
func ProductFunctionDelete(productFunctionIds []string, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)

	err := dbClient.ProductFunctionDelete(productFunctionIds)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	return nil
}

// 更新产品功能
func UpdateProductFunction(productFunction models.ProductFunction, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.UpdateProductFunction(productFunction)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	lc.Debugf("产品功能更新完成")
	return nil
}
